#include "VarFileManager.h"
using namespace Managers;
using namespace Entities;

VarFileManager::VarFileManager(string path) :
	FileManager(path) {
}

void VarFileManager::readRecord(IRecordable* entityToFill, unsigned int startingPosition) {

	unsigned int fullSize = 0;
	unsigned int bufferSize = 0;
	char* buffer;

	openFile();

		//reading header
		fileStream.seekg(startingPosition, ios::beg);
		fileStream.read((char*)&fullSize, sizeof(int));

		//setting the buffer
		bufferSize = (fullSize - sizeof(int));
		buffer = new char[bufferSize];

		//writing into buffer
		fileStream.read(buffer, bufferSize);

	closeFile();

	//filling the Entity
	entityToFill->fillEntity(buffer, bufferSize);
	entityToFill->setEntityID(startingPosition);

	delete buffer;
}


void VarFileManager::updateRecord(IRecordable* toModify,unsigned int offset){
	char* buffer = toModify->buildBuffer();
	int bufferSize = toModify->getBufferSize();

	openFile();

		//writing header
	fileStream.seekp(offset, ios::beg);
	fileStream.write(buffer,bufferSize);

	closeFile();
}

unsigned int VarFileManager::writeRecord(IRecordable* toInsert) {

	char* buffer = toInsert->buildBuffer();
	int bufferSize = toInsert->getBufferSize();
	unsigned int writePosition = 0;

	openFile();

		fileStream.seekp(0, ios::end);
		writePosition = fileStream.tellp();
		fileStream.write(buffer,bufferSize);

	closeFile();

	delete buffer;
	return writePosition;
}

bool VarFileManager::eraseRecord(IRecordable* record) {
	return false;
}

bool VarFileManager::isEndOfFile(unsigned int offset){

	openFile();
	fileStream.seekg(0, ios::end);
	unsigned int finalOffset = fileStream.tellg();
	if (finalOffset == offset) {
		closeFile();
		return true;
	} else {
		closeFile();
		return false;
	}
}

VarFileManager::~VarFileManager() {
}

